package com.cooge.sharevideo.web.controller;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.cooge.sharevideo.base.BaseController;

/**
 * 与谷歌浏览器交互数据用于抓取动态数据
 * 
 * @author 楚平
 * 
 */
@Controller
@RequestMapping("chrome")
public class ChromeController extends BaseController {

	private static Map<String, String> inurlMap = new HashMap<String, String>();
	private static Map<String, String> outurlMap = new HashMap<String, String>();

	@RequestMapping(value = "posturl.html", method = RequestMethod.GET)
	public void postUrl(HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String url = request.getParameter("url");
		System.out.println(url);
		inurlMap.put(url, url);
		while (true) {
			Thread.sleep(1000);
			String value = outurlMap.get(url);
			if (value != null) {
				outurlMap.remove(url);
				PrintWriter pw = new PrintWriter(response.getOutputStream());
				pw.write(value);
				pw.flush();
				pw.close();
				response.getOutputStream().flush();
				response.getOutputStream().close();
				break;
			}
		}
	}

	@RequestMapping(value = "changeurl.html", method = RequestMethod.POST)
	public void changeurl(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		if (inurlMap.size() == 0) {
			PrintWriter pw = new PrintWriter(response.getOutputStream());
			pw.write("false");
			pw.flush();
			pw.close();
		} else {

			Set<Entry<String, String>> se = inurlMap.entrySet();
			Iterator<Entry<String, String>> it = se.iterator();
			if (it.hasNext()) {
				Entry<String, String> en = it.next();
				String url = inurlMap.get(en.getKey());
				inurlMap.remove(en.getKey());
				PrintWriter pw = new PrintWriter(response.getOutputStream());
				pw.write(url);
				pw.flush();
				pw.close();
			}
		}

	}
	@RequestMapping(value = "changedata.html", method = RequestMethod.POST)
	public void changedata(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
			String data = request.getParameter("data");
			System.out.println(data);
			String  d[] = data.split("-###-");
			String url = d[0];
			String data_ = d[1];
			outurlMap.put(url, data_);
			PrintWriter pw = new PrintWriter(response.getOutputStream());
			pw.write("ok");
			pw.flush();
			pw.close();
			
	}
	@RequestMapping(value = "index.html", method = RequestMethod.GET)
	public ModelAndView index(){
		ModelAndView mav=new ModelAndView("chrome");
		return mav;
		
	}

}
